package com.JingYan.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

import java.time.Duration;

/**
 * @author DongJiaQi
 * @create 2022/8/19 15:16
 * @Description: ES 启动配置类
 */
@Configuration
public class ElasticSearchClientConfig  extends AbstractElasticsearchConfiguration {
    /**
     * 协议
     */
    @Value("${elasticsearch.schema:http}")
    private String schema;

    /**
     * 集群地址，如果有多个用“,”隔开
     */
    @Value("${elasticsearch.address}")
    private String address;

    /**
     * 连接超时时间
     */
    @Value("${elasticsearch.connectTimeout}")
    private int connectTimeout;

    /**
     * Socket 连接超时时间
     */
    @Value("${elasticsearch.socketTimeout}")
    private int socketTimeout;

    /**
     * 获取连接的超时时间
     */
    @Value("${elasticsearch.connectionRequestTimeout}")
    private int connectionRequestTimeout;

    /**
     * 最大连接数
     */
    @Value("${elasticsearch.maxConnectNum}")
    private int maxConnectNum;

    /**
     * 最大路由连接数
     */
    @Value("${elasticsearch.maxConnectPerRoute}")
    private int maxConnectPerRoute;

    @Value("${elasticsearch.UserName:}")
    private String userName;

    @Value("${elasticsearch.Password:}")
    private String password;

    @Value("${elasticsearch.port}")
    private int port;
    //配置RestHighLevelClient依赖到spring容器中待用

    public static final RequestOptions COMMON_OPTIONS;
    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        // builder.addHeader("Authorization", "Bearer " + TOKEN);
        // builder.setHttpAsyncResponseConsumerFactory(
        //        new HttpAsyncResponseConsumerFactory
        //                  .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    @Override
    public RestHighLevelClient elasticsearchClient() {
        ClientConfiguration.TerminalClientConfigurationBuilder builder = ClientConfiguration.builder()
                .connectedTo(address)
                .withConnectTimeout(Duration.ofSeconds(30))
                .withSocketTimeout(Duration.ofSeconds(60));
        if(StrUtil.isNotEmpty(userName)){
            builder = builder.withBasicAuth(userName, password);
        }
        final ClientConfiguration clientConfiguration = builder
                .build();
        return RestClients.create(clientConfiguration).rest();

    }

    /*@Bean
    public ElasticsearchClient elasticsearchClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
        List<HttpHost> hostLists = new ArrayList<>();
        String[] hostList = address.split(",");
        for (String addr : hostList) {
            String host = addr.split(":")[0];
            String port = addr.split(":")[1];
            hostLists.add(new HttpHost(host, Integer.parseInt(port), schema));
        }
        // 转换成 HttpHost 数组
        HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{});
        // Create the low-level client


        RestClient restClient = RestClient.builder(httpHost)
                .setHttpClientConfigCallback(
                        httpClientBuilder -> {
                            //设置信任ssl访问
                            SSLContext sslContext = SSLContexts.createDefault();
                            // 设置协议http和https对应的处理socket链接工厂的对象
                            Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder
                                    .<SchemeIOSessionStrategy>create()
                                    .register("http", NoopIOSessionStrategy.INSTANCE)
                                    .register("https", new SSLIOSessionStrategy(sslContext))
                                    .build();
                            httpClientBuilder.setKeepAliveStrategy(((httpResponse, httpContext) -> Duration.ofMinutes(3).toMillis()))
                                    //.disableAuthCaching()
                                    .setDefaultCredentialsProvider(credentialsProvider);
                            return httpClientBuilder;
                        }).build();
        // Create the transport with a Jackson mapper
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        // And create the API client
        return new ElasticsearchClient(transport);
    }*/

}
